package cpm.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import java.util.List;

/**
 * 自定义负载均衡规则
 * @author dell
 */
public class NewRule extends AbstractLoadBalancerRule {

    /**
     * total = 0 （调用总次数）每个服务调用3次 当total=3时指针往下走
     *
     *  total = 0  当total==3以后，我们指针才能往下走，
     *  index = 0 // 当前对外提供服务的服务器地址，
     *  total需要重新置为零，但是已经达到过一个3次，我们的index = 1
     *  分析：我们3次，但是微服务只有8001 8002
     */

    private int total = 0;

    private int currentIndex = 0;

    public Server choose(ILoadBalancer lb,Object key)
    {
        if (lb == null) {
            return null;
        }
        Server server = null;

        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            List<Server> upList = lb.getReachableServers();
            List<Server> allList = lb.getAllServers();

            int serverCount = allList.size();
            if (serverCount == 0) {

                return null;
            }

            if(total < 3)
            {
                server = upList.get(currentIndex);
                total++;
            }else {
                total = 0;
                currentIndex++;
                if(currentIndex >= upList.size())
                {
                    currentIndex = 0;
                }
            }

            if (server == null) {
                Thread.yield();
                continue;
            }

            if (server.isAlive()) {
                return (server);
            }

            server = null;
            Thread.yield();
        }
        return server;
    }


    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(),key);
    }
}
